/**
 * MIT License
 * <p>
 * Copyright (c) 2017-2018 nuls.io
 * <p>
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * <p>
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * <p>
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package io.nuls.klines.scheduled;

import io.nuls.core.parse.JSONUtils;
import io.nuls.klines.constant.Constant;
import io.nuls.klines.service.AppService;
import io.nuls.klines.util.AppUtil;
import io.nuls.klines.util.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * 同步交易对定时任务
 *
 * @author: PierreLuo
 * @date: 2020-04-15
 */
@Component
@Slf4j
@EnableScheduling
public class SyncTradingScheduled {
    @Resource
    private AppService appService;

    private SyncError syncError = new SyncError();
    /**
     * 每天早上7点钟，从币安获取所有交易对信息
     * 只存储其中xxx/USDT的交易对到数据库里
     */
    @Scheduled(cron = "0 0 7 * * *")
    public void execute() {
        if (syncError.isError()) {
            log.error("同步交易对，新增前一天的交易K线，发生错误");
            return;
        }
        log.info("同步交易对");
        try {
            String exchangeInfo = (String) CacheUtil.get("exchangeInfo");
            if (exchangeInfo == null) {
                exchangeInfo = AppUtil.getWithProxy(Constant.EXCHANGEINFO_URL, null, StandardCharsets.UTF_8.name());
                CacheUtil.add("exchangeInfo", exchangeInfo);
            }
            Map<String, Object> map = JSONUtils.json2map(exchangeInfo);
            List<Map> symbolsMap = (List<Map>) map.get("symbols");
            appService.saveExchangeInfo(symbolsMap);
        } catch (Exception e) {
            log.error("sync trading error ", e);
            syncError.setError();
        }
    }

}
